package isquirrel.servlets;

import isquirrel.UserManager;
import isquirrel.beans.User;
import isquirrel.servlets.handler.HttpDBServlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.json.JSONObject;
public class LoginUser extends HttpDBServlet {
	
	private static final long serialVersionUID = 1L;
       
    public LoginUser() {
        super();
    }

    @Override
	protected void handlePost() throws ServletException, IOException, JSONException {

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		JSONObject jsonResponse = new JSONObject();
		
		boolean error = false;
		
		if (username.equals("")) {
			jsonResponse.put("username","Pst, you didn't put a username..");
			error = true;
		}
		if (password.equals("")) {
			if (error){
				jsonResponse.put("password",".. and a password!");
			}
			else{
				jsonResponse.put("password","Pst, you didn't put a password..");
				error = true;
			}
		}
		
		if (!error) {
			
			if (UserManager.loginUser(username, password)) { //valid login credentials
				HttpSession session = request.getSession(true);
				User u = UserManager.getUser(username);
				
				session.setAttribute("user", username);
				session.setAttribute("uid",u.getUserID());
				session.setAttribute("UserBean", u);
				response.getWriter().print("OK");
				return;
			} else {
				jsonResponse.put("ERROR", "Invalid username or password.");
			}
		}	
		writeAjaxResponse(jsonResponse);
	}

    @Override
	protected void handleGet() throws ServletException, IOException, JSONException {
    	    	
	}

}
